package com.intertid.szjk.web;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.intertid.document.ws.DocumentService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.intertid.document.ws.DocumentVO;
import com.intertid.document.ws.SaveDocumentResult;
import com.intertid.szjk.Ws.AttachInfo;
import com.intertid.szjk.Ws.DateUtil;
import com.intertid.szjk.Ws.HtmlUtil;
import com.intertid.szjk.Ws.Randomizer;
import com.intertid.szjk.Ws.StringUtil;


@Controller
@Scope("prototype")
@RequestMapping("/szjk")
public class szjkWeb {

	@Autowired
	DocumentService documentService;
	
	@RequestMapping("/lieb")
	@ResponseBody
	public String name(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
	  String s ="";
	  DocumentVO documentVO =new DocumentVO();
	  SaveDocumentResult result = new SaveDocumentResult();
	  documentVO.setDocType(0);
	  
		Long chanId=0l;
		   if(StringUtils.isNotBlank(request.getParameter("chanId"))){
	    	   String chanId2 = request.getParameter("chanId");


	    	   chanId=Long.parseLong(String.valueOf(chanId2));
		
			  
			   documentVO.setChanId(chanId);
		       }
	   
	   
		   documentVO.setStatusId(4L);
		   
	   String title ="";
	   if(StringUtils.isNotBlank(request.getParameter("title"))){
    	   
		   title=request.getParameter("title");
		   documentVO.setTitle(title);
		       }
	   
	   
	   String editor ="";
	   if(StringUtils.isNotBlank(request.getParameter("editor"))){
    	   
		   editor=request.getParameter("editor");
		   documentVO.setCruser(StringUtil.isNotEmpty(editor) ? editor
					: "admin");
       	  documentVO.setAuthor(StringUtil.isNotEmpty(editor) ? editor
 					: "admin");
		       }
	   
	   Date currentDate= new Date();
	   String WriteTime ="";
	   if(StringUtils.isNotBlank(request.getParameter("WriteTime"))){
    	   
		   WriteTime=request.getParameter("WriteTime");
		   
		   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
		   try {
			currentDate = sdf.parse(WriteTime);
		} catch (ParseException e) {
			
			e.printStackTrace();
		}
		   documentVO.setWriteTime(currentDate);
	
		       }
	   
	   
	    
	   String image ="";
	   if(StringUtils.isNotBlank(request.getParameter("image"))){
    	   
		   image=request.getParameter("image");
				   String attachExt = image.substring(image.lastIndexOf(".") + 1);
				   String ecmFileName = getRandomAppendixPatha(currentDate, attachExt);
				   String ecmFileNames = getRandomAppendixPathb(currentDate, attachExt);
				   String ecmFileNamess = ecmFileName+ecmFileNames;
				   documentVO.setPicUrl(ecmFileNamess);
				   szjkWeb.downLoadFromUrl(image,ecmFileNames,"E:/turboECM2.1.7/ecmdata"+ecmFileName);
		       }
	   
	   
	   

	   String Content ="";
	   if(StringUtils.isNotBlank(request.getParameter("Content"))){
		   
		 //Content =HtmlUtil.getBodyHtml(request.getParameter("Content"));
			Content =StringEscapeUtils.unescapeHtml(request.getParameter("Content"));
			Content =HtmlUtil.getBodyHtml(request.getParameter("Content"));
      }
	 
	   List<AttachInfo> docAttachInfos = Lists.newArrayList();
	   Content= szjkWeb.replaceFileName(Content,
					docAttachInfos,
					(documentVO.getWriteTime() == null ? new Date()
							: documentVO.getWriteTime()));
		documentVO.setDocContent(Content);
	
	
	   try {
		   if(chanId!=0l){
		   result = documentService.saveDocument(documentVO);
		   
		   s="上传成功";
		   }else{
			 
			   s="上传失败";
		   }
		   
	} catch (Exception e) {
		// TODO: handle exception
		System.out.print("g");
		 s="上传失败"; 
	}
	   
	  return s;
		
		
	}
	
	
    /** 
     * 从网络Url中下载文件 
     * @param urlStr 
     * @param fileName 
     * @param savePath 
     * @throws IOException 
     */  
    public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{  
    	
    	
    	   
        File fp = new File(savePath);    
        // 创建目录    
        if (!fp.exists()) {    
            fp.mkdirs();// 目录不存在的情况下，创建目录。    
        }  
    	
    	
        URL url = new URL(urlStr);    
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
                //设置超时间为3秒  
        conn.setConnectTimeout(3*1000);  
        //防止屏蔽程序抓取而返回403错误  
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
  
        //得到输入流  
        InputStream inputStream = conn.getInputStream();    
        //获取自己数组  
        byte[] getData = readInputStream(inputStream);      
  
        //文件保存位置  
        File saveDir = new File(savePath);  
        if(!saveDir.exists()){  
            saveDir.mkdir();  
        }  
        File file = new File(saveDir+File.separator+fileName);      
        FileOutputStream fos = new FileOutputStream(file);       
        fos.write(getData);   
        if(fos!=null){  
            fos.close();    
        }  
        if(inputStream!=null){  
            inputStream.close();  
        }  
  
  
        System.out.println("info:"+url+" download success");   
  
    }  
  
  
  
    /** 
     * 从输入流中获取字节数组 
     * @param inputStream 
     * @return 
     * @throws IOException 
     */  
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {    
        byte[] buffer = new byte[1024];    
        int len = 0;    
        ByteArrayOutputStream bos = new ByteArrayOutputStream();    
        while((len = inputStream.read(buffer)) != -1) {    
            bos.write(buffer, 0, len);    
        }    
        bos.close();    
        return bos.toByteArray();    
    }    
  
    public static String replaceFileName(String htmlFile,
			List<AttachInfo> docAttachInfos, Date currentDate) {

		//htmlFile = htmlFile.replaceAll("http://54.223.71.188", "");

		System.out.println("前台传的html==="+htmlFile);
		// HTML解析
		org.jsoup.nodes.Document doc = Jsoup.parse(htmlFile);
		System.out.println("jsoup解析的doc===="+doc);
		Map<String, String> replacedMaps = new HashMap<String, String>();
	
		AttachInfo attachInfo = new AttachInfo();
		
		
		
		
		org.jsoup.select.Elements hrefs = doc.getElementsByTag("a");
		for (Element h : hrefs) {
			String href = h.attr("href");

	
			// 替换过的资源跳过
		
			String AttachType = ".jpg|.gif|.bmp|.jpeg|.doc|.docx|.ppt|.pptx|.xls|.xlsx|.txt|.rar|.zip|.pdf|.flv|.rm|.mp3|.mp4|.wav|.wmv|.swf";

		
			String attachExt = href.substring(href.lastIndexOf(".") + 1);
		

			if (href.indexOf("?") != -1)
				href = href.substring(href.lastIndexOf("=") + 1);

			// System.out.println("----附件----" + href);
			String ecmFileNames = getRandomAppendixPatha(currentDate, attachExt);
			   String ecmFileNamess = getRandomAppendixPathb(currentDate, attachExt);
			String ecmFileName = getRandomAppendixPath(currentDate, attachExt);
			htmlFile = StringUtil.replace(htmlFile, href, ecmFileName);
            System.out.println("位置+++++++++++"+ecmFileNames);
            System.out.println("名称+++++++++++"+ecmFileNamess);
            System.out.println("综合+++++++++++"+ecmFileName);
			attachInfo = new AttachInfo();
			attachInfo.setCmsFileName(href);
			attachInfo.setEcmFileName(ecmFileName);
			
			   try {
					szjkWeb.downLoadFromUrl(href,ecmFileNamess,"E:/turboECM2.1.7/ecmdata"+ecmFileNames);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			if (!docAttachInfos.contains(attachInfo)) {
				docAttachInfos.add(attachInfo);
			}
			replacedMaps.put(href, "");

		}
		
		
		
		
		
		
		
		
		// image
		org.jsoup.select.Elements images = doc.getElementsByTag("img");
		System.out.println("images的个数===="+images.size());
		for (Element image : images) {
			String src = image.attr("src");
		

			String attachExt = src.substring(src.lastIndexOf(".") + 1);
			String ecmFileNames = getRandomAppendixPatha(currentDate, attachExt);
			   String ecmFileNamess = getRandomAppendixPathb(currentDate, attachExt);
			String ecmFileName = ecmFileNames+ecmFileNamess;
			htmlFile = StringUtil.replace(htmlFile, src, ecmFileName);

			attachInfo = new AttachInfo();
			attachInfo.setCmsFileName(src);
			attachInfo.setEcmFileName(ecmFileName);
			
			   
			   try {
				szjkWeb.downLoadFromUrl(src,ecmFileNamess,"E:/turboECM2.1.7/ecmdata"+ecmFileNames);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			   
			if (!docAttachInfos.contains(attachInfo)) {
				docAttachInfos.add(attachInfo);
			}

			replacedMaps.put(src, "");
			
			

  
		}

		return htmlFile;
	}
    
    
	public static String getRandomAppendixPath(Date currentDate, String fileExt) {
		String appendixPath = "";
		String yearAndMonth = DateUtil.toString(currentDate, "yyyyMM");
		String day = DateUtil.toString(currentDate, "dd");
		appendixPath = "/uploadfiles/" + yearAndMonth + "/" + day + "/"
				+ getRandomAppendixFileName(currentDate) + "." + fileExt;
		return appendixPath;
	} 
	
	
	//路径
	public static String getRandomAppendixPatha(Date currentDate, String fileExt) {
		String appendixPath = "";
		String yearAndMonth = DateUtil.toString(currentDate, "yyyyMM");
		String day = DateUtil.toString(currentDate, "dd");
		appendixPath = "/uploadfiles/" + yearAndMonth + "/" + day + "/";
		return appendixPath;
	} 
	
	//文件名
	public static String getRandomAppendixPathb(Date currentDate, String fileExt) {
		String appendixPath = "";
		String yearAndMonth = DateUtil.toString(currentDate, "yyyyMM");
		String day = DateUtil.toString(currentDate, "dd");
		appendixPath =  getRandomAppendixFileName(currentDate) + "." + fileExt;
		return appendixPath;
	} 
	
	public static String getRandomAppendixFileName(Date currentDate) {
		String currDateTime = DateUtil.toString(currentDate, "yyyyMMddHHmmss");
		String randomNum = String.valueOf(Randomizer.getInstance().nextInt(
				100000000));
		if (randomNum.toString().length() < 8) {
			for (int i = 0; i < 8 - randomNum.toString().length(); i++) {
				randomNum = "0" + randomNum;
			}
		}
		return currDateTime + randomNum;
	}
    
}
